package com.cloud.template.base.util;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CsvExportUtil {
	private static final Logger LOGGER= LogManager.getLogger(CsvExportUtil.class);
	
	/**
	   * 生成为CVS文件 
	   * @param exportData
	   *       源数据List
	   * @param titleList
	   *       csv文件的列表头map
	   * @param outPutPath
	   *       文件路径
	   * @param fileName
	   *       文件名称
	   * @return
	   */
	  public static File createCSVFile(List<Object[]> exportData, LinkedList<String> titleList,
                                       String outPutPath, String fileName) {
		  LOGGER.info("生成为CVS文件 开始，文件名："+fileName);
	    File csvFile = null;
	    BufferedWriter csvFileOutputStream = null;
	    try {
	      //定义文件名格式并创建
	      csvFile = new File(outPutPath+fileName+".csv");
	    		  //File.createTempFile(fileName, ".csv", new File(outPutPath));
	      // UTF-8使正确读取分隔符"," 
	      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
	        csvFile), "UTF-8"), 1024);
	      System.out.println("csvFileOutputStream：" + csvFileOutputStream);
	      // 写入文件头部 
	      for (Iterator<String> propertyIterator = titleList.iterator(); propertyIterator.hasNext();) {
	        String title = propertyIterator.next();
	        csvFileOutputStream.write(title != null ? title : "");
	        if (propertyIterator.hasNext()) {
	          csvFileOutputStream.write(",");
	        }
	      }
	      csvFileOutputStream.newLine();
	      // 写入文件内容 
	      for (Iterator<Object[]> iterator = exportData.iterator(); iterator.hasNext();) {
	        Object[] row = iterator.next();
	        for (int i = 0;i<titleList.size();i++) {
	          csvFileOutputStream.write(row[i]==null?"":row[i].toString());
	          if (i != titleList.size()-1) {
	            csvFileOutputStream.write(",");
	          }
	        }
	        if (iterator.hasNext()) {
	          csvFileOutputStream.newLine();
	        }
	      }
	      csvFileOutputStream.flush();
	    } catch (Exception e) {
	    	LOGGER.error("生成csv文件失败",e);
	    } finally {
	      try {
	        csvFileOutputStream.close();
	      } catch (IOException e) {
	    	  LOGGER.error(e);
	      }
	    }
	    return csvFile;
	  }
}
